<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts'
import anlyze from '../../apis/anlyze.js'

const { t, locale } = useI18n()
const chart = ref(null)
let myChart = null
const loading = ref(false)
const error = ref(false)

const starConfig = [
  { name: t('oneStar'), color: '#FF6B6B', minDisplay: 0 },
  { name: t('twoStar'), color: '#FFA36B', minDisplay: 0 },
  { name: t('threeStar'), color: '#FFD166', minDisplay: 0 },
  { name: t('fourStar'), color: '#06D6A0', minDisplay: 0 },
  { name: t('fiveStar'), color: '#118AB2', minDisplay: 0 }
]

const initChart = () => {
  if (myChart) {
    myChart.dispose()
  }
  
  // 确保DOM已经渲染
  if (chart.value) {
    myChart = echarts.init(chart.value)
    
    // 设置响应式
    const resizeHandler = () => {
      myChart && myChart.resize()
    }
    
    window.addEventListener('resize', resizeHandler)
    
    // 组件卸载时移除事件监听
    onUnmounted(() => {
      window.removeEventListener('resize', resizeHandler)
      myChart && myChart.dispose()
    })
  }
}

const fetchStarRatingData = async () => {
  loading.value = true
  error.value = false
  
  try {
    const res = await anlyze.getTaskRating()
    const ratingData = res || [0, 0, 0, 0, 0]
    
    // 确保图表已初始化
    if (!myChart) {
      initChart()
    }

    // 检查是否有数据
    const hasData = ratingData.some(v => v > 0)

    const option = {
      title: {
        text: t('taskStarDistribution'),
        left: 'center',
        top: 10,
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: params => {
          const value = params.value === 0 ? t('none') : params.value + ' ' + t('items')
          return `${params.name}<br/>${t('quantity')}: ${value} (${params.percent}%)`
        },
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: '#e6e9ed',
        borderWidth: 1,
        textStyle: {
          color: '#5e6d82'
        },
        extraCssText: 'box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);'
      },
      legend: {
        orient: 'horizontal',
        bottom: 10,
        left: 'center',
        data: starConfig.map(item => item.name),
        itemHeight: 12,
        itemWidth: 12,
        itemGap: 20,
        textStyle: {
          color: '#5e6d82',
          fontSize: 12
        }
      },
      series: [{
        name: t('starDistribution'),
        type: 'pie',
        radius: ['35%', '65%'],
        center: ['50%', '45%'], // 调整圆饼图位置，为底部图例留出空间
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: hasData,
          formatter: params => {
            return params.value > 0 ? `${params.name}\n${params.value} ${t('items')}` : ''
          },
          fontSize: 12,
          lineHeight: 16,
          color: '#5e6d82',
          position: 'outside',
          alignTo: 'edge',
          edgeDistance: '10%',
          distanceToLabelLine: 5
        },
        labelLine: {
          show: hasData,
          length: 15,
          length2: 10,
          smooth: true
        },
        data: starConfig.map((item, index) => ({
          name: item.name,
          value: ratingData[index] || 0,
          itemStyle: { color: item.color },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            label: {
              fontSize: 14,
              fontWeight: 'bold'
            }
          }
        })),
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        }
      }]
    }

    // 如果没有数据，添加提示文本
    if (!hasData) {
      option.graphic = [{
        type: 'text',
        left: 'center',
        top: '45%',
        style: {
          text: t('noStarData'),
          fill: '#999',
          fontSize: 16
        }
      }]
    }

    myChart.setOption(option)
    loading.value = false
  } catch (error) {
    console.error(t('getStarDataFailed') + ':', error)
    loading.value = false
    error.value = true
  }
}

// 监听语言变化，重新加载图表
watch(locale, () => {
  // 更新星级配置
  starConfig[0].name = t('oneStar')
  starConfig[1].name = t('twoStar')
  starConfig[2].name = t('threeStar')
  starConfig[3].name = t('fourStar')
  starConfig[4].name = t('fiveStar')
  
  fetchStarRatingData()
})

onMounted(() => {
  initChart()
  fetchStarRatingData()
})
</script>

<template>
  <div class="chart-container">
    <div v-if="loading" class="loading-overlay">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <div class="loading-text">{{ $t('loading') }}</div>
    </div>
    
    <div v-if="error" class="error-overlay">
      <el-icon class="error-icon"><Warning /></el-icon>
      <div class="error-text">{{ $t('getStarDataFailed') }}</div>
      <el-button size="small" @click="fetchStarRatingData" class="retry-button">
        {{ $t('retryButton') }}
      </el-button>
    </div>
    
    <div ref="chart" class="chart-content"></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.chart-content {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}

.loading-overlay, .error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.loading-icon, .error-icon {
  font-size: 32px;
  margin-bottom: 12px;
  color: #909399;
}

.loading-text, .error-text {
  font-size: 14px;
  color: #606266;
}

.retry-button {
  margin-top: 12px;
  background: linear-gradient(135deg, #409eff, #53a8ff);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.retry-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

@media (max-width: 768px) {
  .chart-container {
    height: 450px;
  }
  
  .loading-icon, .error-icon {
    font-size: 24px;
  }
  
  .loading-text, .error-text {
    font-size: 12px;
  }
}
</style>
